﻿using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using iPhOwa.Exchange.ContentClasses;
using iPhOwa.Exchange.Managers;
using iPhOwa.Web.Properties;

namespace iPhOwa.Web
{
	/// <summary>
	/// Compose message.
	/// </summary>
	public partial class ComposeMessage : iPhOwaPage
	{
		/// <summary>
		/// Page load event.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")]
		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				Title = string.Format(CultureInfo.CurrentUICulture, "Compose Message - {0}", Settings.Default.Title);

				ViewState["UrlReferrer"] = Request.UrlReferrer;
				string action = Request["action"] ?? "new";

				switch(action.ToLowerInvariant())
				{
					case "reply":
						{
							Message message = MessageManager.Get(Path, OwaSession);

							if(message == null)
							{
								throw new ApplicationException("Expected message, but got something else.");
							}

							toTextBox.Text = message.From;
							subjectTextBox.Text = "RE: " + message.NormalizedSubject;
							bodyTextBox.Text = BuildReplyBody(message);

							break;
						}

					case "replyall":
						{
							Message message = MessageManager.Get(Path, OwaSession);

							if(message == null)
							{
								throw new ApplicationException("Expected message, but got something else.");
							}

							toTextBox.Text = string.Format(CultureInfo.InvariantCulture, "{0}; {1}", message.From, message.To);
							ccTextBox.Text = message.CC;
							subjectTextBox.Text = "RE: " + message.NormalizedSubject;
							bodyTextBox.Text = BuildReplyBody(message);

							break;
						}

					case "forward":
						{
							Message message = MessageManager.Get(Path, OwaSession);

							if(message == null)
							{
								throw new ApplicationException("Expected message, but got something else.");
							}

							subjectTextBox.Text = "FW: " + message.NormalizedSubject;
							bodyTextBox.Text = BuildForwardBody(message);

							break;
						}

					default:

						{
							string to = Request["to"];

							if(!string.IsNullOrEmpty(to))
							{
								toTextBox.Text = to;
							}
						}

						break;
				}
			}
		}

		private static string BuildForwardBody(Message message)
		{
			var sb = new StringBuilder();
			sb.AppendLine();
			sb.AppendLine();
			sb.AppendLine();
			sb.AppendLine("---------- Forwarded Message ----------");
			sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "From: {0}", message.From));
			sb.AppendLine(string.Format(CultureInfo.CurrentUICulture, "Date: {0:g}", message.DateReceived));
			sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "Subject: {0}", message.Subject));
			sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "To: {0}", message.To));

			if(!string.IsNullOrEmpty(message.CC))
			{
				sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "CC: {0}", message.CC));
			}

			sb.AppendLine();
			sb.Append(message.TextDescription.Trim());

			return sb.ToString();
		}

		private static string BuildReplyBody(Message message)
		{
			var sb = new StringBuilder();
			sb.AppendLine();
			sb.AppendLine();
			sb.AppendLine();
			sb.AppendLine(string.Format(CultureInfo.CurrentUICulture, "On {0:g}, {1} wrote:", message.DateReceived, message.From));
			sb.AppendLine();

			string[] lines = message.TextDescription.Trim().Split('\n');

			foreach(string line in lines)
			{
				sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "> {0}", line.Trim()));
			}

			return sb.ToString();
		}

		/// <summary>
		/// Cancel button click event.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void CancelButton_Click(object sender, EventArgs e)
		{
			RedirectToReferrer();
		}

		private void RedirectToReferrer()
		{
			string referrer = "~/Default.aspx";

			if(ViewState["UrlReferrer"] != null)
			{
				referrer = ((Uri)ViewState["UrlReferrer"]).PathAndQuery;
			}

			Response.Redirect(referrer);
		}

		/// <summary>
		/// Send button click event.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void SendButton_Click(object sender, EventArgs e)
		{
			string subject = subjectTextBox.Text.Trim();
			string cc = ccTextBox.Text.Trim();

			var sb = new StringBuilder();
			sb.AppendFormat("To: {0}\n", toTextBox.Text.Trim().Replace(',', ';'));

			if(!string.IsNullOrEmpty(cc))
			{
				sb.AppendFormat("CC: {0}\n", cc).Replace(',', ';');
			}

			sb.AppendFormat("Subject: {0}\n", subject);
			sb.AppendFormat("Date: {0}\n", DateTime.Now);
			sb.Append("X-Mailer: iPhOwa\n");
			sb.Append("MIME-Version: 1.0\n");
			sb.Append("Content-Type: text/plain;\n");
			sb.Append("Charset = \"iso-8859-1\"\n");
			sb.Append("Content-Transfer-Encoding: 8bit\n\n");
			sb.Append(bodyTextBox.Text.Trim());

			var saveToUri = new Uri(string.Format(CultureInfo.InvariantCulture, "{0}{1}.eml", DraftsUrl, subject.Replace("/", "_xF8FF_")));

			MessageManager.Send(saveToUri, MailSubmissionUrl, sb.ToString(), OwaSession);

			RedirectToReferrer();
		}
	}
}